Enum(列舉型別)
用途:定義一組固定常數值,讓程式更清楚且安全。
不用靠數字或字串表示狀態,程式更安全。
避免拼字錯誤或使用無效值。
Exception(例外)
例外是程式執行中發生的「異常狀況」,可能會導致程式崩潰。
例如:
除以 0 → ArithmeticException
陣列超出範圍 → ArrayIndexOutOfBoundsException
將字串轉數字錯誤 → NumberFormatException
--Java 提供 try / catch / finally 機制,讓程式能「安全處理錯誤」。
1 try
嘗試執行可能會出錯的程式。
如果沒錯誤,catch 不會執行。
2 catch
捕捉特定 Exception,程式不會崩潰。
例如:NumberFormatException 處理非整數輸入。
3 finally
無論是否發生例外,都會執行。
常用來關閉資源,例如 Scanner、檔案、網路連線。
--Unchecked Exception(RuntimeException 子類)
ArithmeticException 算術錯誤(如除以 0)
NullPointerException 物件為 null 時呼叫方法或屬性
ArrayIndexOutOfBoundsException 陣列存取超出範圍
ClassCastException 類型轉換錯誤
IllegalArgumentException 傳入不合法參數
NumberFormatException 字串轉數字失敗
--Checked Exception
IOException I/O 操作錯誤(檔案、網路)
FileNotFoundException 檔案不存在
SQLException 資料庫操作錯誤
ClassNotFoundException 找不到指定的類別
InterruptedException 執行緒被中斷
使用 valueOf() 轉換字串成 Enum
使用者輸入字串後可以轉 enum
如果輸入錯誤,就會丟 IllegalArgumentException 被 catch 處理
IllegalArgumentException它屬於 RuntimeException,也就是Unchecked Exception
用強制寫 try-catch,但你可以選擇去捕捉它。
我的程式碼中 valueOf() 會把字串轉成對應的 enum 值,但只要輸入者不是輸入OPEN/CLOSED/TIMEOUt會讓它 丟IllegalArgumentException: